import './SearchBox.scss'
import { useMount } from 'ahooks'
import { useState } from 'react'

import { API_Mapping } from '../../Utils/Api'
import { FormTemplate } from '../../Utils/FormTemp'
import { FieldMapping } from '../../Config/Mapping'

const SearchBox = ({ data, Off }) => {
    const { data: search, fields, searchData, DevEvent } = data
    const [columns, setColumns] = useState()
    const getData = async () => await Promise.all(search.map(async item => {
        let { valueType, dataField, mappingType, mappingData } = fields.find(v => v.dataField === item.value) || {}
        if (item.init === 'default') {
            const data = { title: item.label, dataIndex: dataField, valueType: valueType, isModify: true }
            if (valueType === 'Radio' || valueType === 'Select' || valueType === 'TreeSelect') data.valueEnum = await setMapping(mappingType, mappingData)
            return data
        } else {
            return { title: item.label, dataIndex: item.value, valueType: item.init, picker: item.init, isModify: true }
        }
    }))

    useMount(() => { getData().then(res => { setColumns(res) }) })

    const setMapping = async (mappingType, mappingData) => {
        if (mappingType === 'DataMapping') return FieldMapping[mappingData]
        if (mappingType === 'ApiMapping') return await API_Mapping[mappingData]()
        return []
    }

    DevEvent.useSubscription(val => { if (val.type === 'onSearch') Off() })

    return (
        <div className='SearchBox'>
            {columns && <FormTemplate onSearch columns={columns} DevEvent={DevEvent} init={searchData} />}
        </div>
    );
};

export default SearchBox;